package com.netease.dao;

import com.netease.Buy;
import com.netease.Product;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by meichen on 2018/3/13.
 */
@Repository("BuyDao")
public class BuyDaoImpl implements BuyDao{
    @Autowired
    private SessionFactory sessionFactory;

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    public void insert(Buy buy)throws HibernateException{
        Session session = sessionFactory.openSession();
        Transaction t = session.beginTransaction();
        session.save(buy);
        t.commit();
        session.close();
    }

    public List<Buy> getAllBuy()throws HibernateException{
        Session session = sessionFactory.openSession();
        List<Buy> buys = new ArrayList<Buy>();
        String hql = "from " + Buy.class.getName();
        Query<Buy> query = session.createQuery(hql);
        buys = query.getResultList();
        session.close();
        return buys;
    }
}
